//
//  KLMDateTimePickerView.swift
//  KLM_GN
//
//  Created by Nic on 2025/4/3.
//

import UIKit

<<<<<<< HEAD
<<<<<<< HEAD
private let DefaultPickerWidth = 50.0
private let DefaultPickerExtraWidth = 18.0
private let DefaultUnitWidth = 12.0
private let DefaultYearMinus = 10


// MARK: - 嵌套类型
enum ComponentType: String, CaseIterable {
    case year   = "yyyy"
    case month  = "MM"
    case day    = "dd"
    case hour   = "HH"
    case minute = "mm"
    case second = "ss"
    
    var unitLabel: String {
        switch self {
        case .year:   return "年"
        case .month:  return "月"
        case .day:    return "日"
        case .hour:   return "时"
        case .minute: return "分"
        case .second: return "秒"
        }
    }
}

class KLMDateTimePickerView: UIView {

    // MARK: - 属性
    private var pickerViews = UIView()
    private var components: [ComponentType] = []
    private var pickers: [UIPickerView] = []
    private var labels: [UILabel] = []
    var dateComponents = DateComponents()
    /// 当前时间组件，用于补齐传入的初始化日期缺省组件
    var currentDateComponents = DateComponents()
    
    var dateFormat: String = "yyyy-MM-dd HH:mm" {
        didSet { parseDateFormat() }
    }
    
    var showUnitLabels = false
    var onDateSelected: ((Date, String) -> Void)?
    
    var onConfirm: (() -> Void)?
    var onCancel: (() -> Void)?
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    // MARK: - UI配置
    private func setupUI() {
        currentDateComponents = getCurrentDateComponents()
        setupPickerStack()
        setupControlButtons()
        
        parseDateFormat()
        setupConstraints()
        setupInitialSelections()
    }
    private func setupPickerStack() {
        addSubview(pickerViews)
        pickerViews.translatesAutoresizingMaskIntoConstraints = false
        pickerViews.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
        }
    }
    
    private func setupControlButtons() {
        let buttonView = UIView()
        addSubview(buttonView)
        buttonView.translatesAutoresizingMaskIntoConstraints = false
        buttonView.snp.makeConstraints { make in
            make.bottom.leading.trailing.equalToSuperview()
            make.height.equalTo(50)
            make.top.equalTo(pickerViews.snp.bottom)
        }
        
        let cancelButton = createButton(title: "取消", action: #selector(cancelAction))
        let confirmButton = createButton(title: "确定", action: #selector(confirmAction))
        buttonView.addSubview(cancelButton)
        buttonView.addSubview(confirmButton)
        cancelButton.snp.makeConstraints { make in
            make.leading.bottom.top.equalToSuperview()
            make.trailing.equalTo(confirmButton.snp.leading)
        }
        confirmButton.snp.makeConstraints { make in
            make.trailing.bottom.top.equalToSuperview()
            make.width.equalTo(cancelButton)
        }
        let topLine = UIView()
        let middleLine = UIView()
        topLine.backgroundColor = rgba(242, 242, 242, 1)
        middleLine.backgroundColor = rgba(242, 242, 242, 1)
        buttonView.addSubview(topLine)
        buttonView.addSubview(middleLine)
        topLine.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.height.equalTo(0.5)
        }
        middleLine.snp.makeConstraints { make in
            make.height.equalToSuperview()
            make.centerX.equalToSuperview()
            make.width.equalTo(0.5)
        }
    }
    // MARK: - 日期处理
    private func parseDateFormat() {
        components.removeAll()
        let pattern = "(yyyy|MM|dd|HH|mm|ss)"
        let regex = try! NSRegularExpression(pattern: pattern)
        let matches = regex.matches(in: dateFormat, range: NSRange(dateFormat.startIndex..., in: dateFormat))
        
        for match in matches {
            guard let range = Range(match.range, in: dateFormat) else { continue }
            let componentStr = String(dateFormat[range])
            if let component = ComponentType(rawValue: componentStr) {
                components.append(component)
            }
        }
        createPickers()
    }
    private func createPickers() {
        pickers.forEach { $0.removeFromSuperview() }
        labels.forEach { $0.removeFromSuperview() }
        pickers.removeAll()
        labels.removeAll()
        
        if showUnitLabels {
            for (index, component) in components.enumerated() {
                let picker = UIPickerView()
                picker.dataSource = self
                picker.delegate = self
                pickers.append(picker)
                pickerViews.addSubview(picker)
                let width = component == .year ? DefaultPickerWidth + 10 : DefaultPickerWidth
                picker.snp.makeConstraints { make in
                    make.top.bottom.equalToSuperview()
                    make.width.equalTo(width)
                    if index == 0 {
                        make.leading.equalToSuperview()
                    }
                }
                
                let label = UILabel()
                label.text = component.unitLabel
                label.font = .systemFont(ofSize: 14)
                labels.append(label)
                label.snp.makeConstraints { make in
                    make.leading.equalTo(picker.snp.trailing)
                    make.centerY.equalTo(picker)
                    if index == components.count - 1 {
                        make.trailing.equalToSuperview()
                    }
                }
            }
        } else {
            let picker = UIPickerView()
            picker.dataSource = self
            picker.delegate = self
            pickers.append(picker)
            pickerViews.addSubview(picker)
            picker.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
    }
    // MARK: - 按钮操作
    @objc private func cancelAction() {
        onCancel?()
    }
    
    @objc private func confirmAction() {
        guard let date = Calendar.current.date(from: dateComponents) else { return }
        let formatter = DateFormatter(format: dateFormat)
        onDateSelected?(date, formatter.string(from: date))
//        dismiss(animated: true)
        onConfirm?()
    }
    private func setupConstraints() {
//        preferredContentSize = CGSize(
//            width: calculateTotalWidth(),
//            height: 240
//        )
    }
    // 调整整体宽度计算
    private func calculateTotalWidth() -> CGFloat {
        let extraWidth = components.contains(where: {$0 == .year}) ? 10.0 : 0.0
        let labelWidth: CGFloat = showUnitLabels ? DefaultUnitWidth : 0
        let totalWidth = CGFloat(components.count) * (DefaultPickerWidth + labelWidth + DefaultPickerExtraWidth) + extraWidth
//        print("预计总长度为：", totalWidth, view.width)
        return totalWidth
    }
    // MARK: - 初始选择设置
    private func setupInitialSelections() {
        var picker = pickers[0]
        var componentIndex = 0
        for (index, component) in components.enumerated() {
            if showUnitLabels {
                picker = pickers[index]
            } else {
                componentIndex = index
            }
            
            switch component {
            case .year:
                let startYear = currentDateComponents.year! - DefaultYearMinus
                let endYear = currentDateComponents.year! + DefaultYearMinus
                if let year = dateComponents.year, (startYear...endYear).contains(year) {
                    picker.selectRow(year - startYear, inComponent: componentIndex, animated: false)
                }
            case .month:
                if let month = dateComponents.month, (1...12).contains(month) {
                    picker.selectRow(month - 1, inComponent: componentIndex, animated: false)
                }
            case .day:
                if let day = dateComponents.day, (1...31).contains(day) {
                    picker.selectRow(day - 1, inComponent: componentIndex, animated: false)
                }
            case .hour:
                if let hour = dateComponents.hour, (0...23).contains(hour) {
                    picker.selectRow(hour, inComponent: componentIndex, animated: false)
                }
            case .minute:
                if let minute = dateComponents.minute, (0...59).contains(minute) {
                    picker.selectRow(minute, inComponent: componentIndex, animated: false)
                }
            case .second:
                if let second = dateComponents.second, (0...59).contains(second) {
                    picker.selectRow(second, inComponent: componentIndex, animated: false)
                }
            }
            // 去掉UIPickerView的默认背景色
            picker.subviews.forEach { subView in
                subView.backgroundColor = .clear
            }
        }
    }
    // MARK: - 获取当天的日期各个组件
    func getCurrentDateComponents() -> DateComponents {
        return Calendar.current.dateComponents(
            [.year, .month, .day, .hour, .minute, .second],
            from: Date()
        )
    }
    private func createButton(title: String, action: Selector) -> UIButton {
        let button = UIButton(type: .custom)
        button.setTitle(title, for: .normal)
        button.setTitleColor((title == "确定" ? appMainThemeColor : rgba(38, 38, 38, 1)), for: .normal)
        button.titleLabel?.font = UIFont(safeName: "Alata-Regular", size: 18)
        button.addTarget(self, action: action, for: .touchUpInside)
        return button
    }
}

extension KLMDateTimePickerView: UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        if showUnitLabels {
            return 1
        } else {
            return components.count
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        var pickIndex = component
        if let index = pickers.firstIndex(of: pickerView), showUnitLabels {
            pickIndex = index
        }
        let type = components[pickIndex]
        
        switch type {
        case .year:
            return DefaultYearMinus * 2 // 当前日期前后10年
        case .month:
            return 12
        case .day:
            let year = dateComponents.year ?? currentDateComponents.year!
            let month = dateComponents.month ?? currentDateComponents.month!
            return daysInMonth(year: year, month: month)
        case .hour:
            return 24
        case .minute, .second:
            return 60
        }
    }
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        var pickIndex = component
        if let index = pickers.firstIndex(of: pickerView), showUnitLabels {
            pickIndex = index
        }
        let type = components[pickIndex]
        var title = ""
        switch type {
            case .year: title = String(format: "%04d", currentDateComponents.year! - DefaultYearMinus + row)
            case .month: title = String(format: "%02d", row + 1)
            case .day: title = String(format: "%02d", row + 1)
            case .hour: title = String(format: "%02d", row)
            case .minute, .second: title = String(format: "%02d", row)
        }
        
        if showUnitLabels {
            let view = UIView()
            guard let _ = pickers.firstIndex(of: pickerView) else { return view }
            
            let label = UILabel()
            label.textAlignment = .center
            label.font = .systemFont(ofSize: 16.0)
            label.text = title
            view.addSubview(label)
            label.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            let topLine = UIView()
            let bottomLine = UIView()
            topLine.backgroundColor = rgba(222, 222, 222, 1)
            bottomLine.backgroundColor = rgba(222, 222, 222, 1)
            view.addSubview(topLine)
            view.addSubview(bottomLine)
            topLine.snp.makeConstraints { make in
                make.leading.trailing.top.equalToSuperview()
                make.height.equalTo(0.5)
            }
            bottomLine.snp.makeConstraints { make in
                make.leading.trailing.bottom.equalToSuperview()
                make.height.equalTo(0.5)
            }
            
            // 当前滚动选择的一行
            let isCurrentSelectRow = pickerView.selectedRow(inComponent: component) == row
            topLine.isHidden = !isCurrentSelectRow
            bottomLine.isHidden = !isCurrentSelectRow
            
            return view
        } else {
            let label = UILabel()
            label.textAlignment = .center
            label.font = .systemFont(ofSize: 16.0)
            label.text = title
            return label
        }
    }
    // MARK: - 计算某年某月的天数
    private func daysInMonth(year: Int, month: Int) -> Int {
        let calendar = Calendar.current
        let date = calendar.date(from: DateComponents(year: year, month: month))!
        return calendar.range(of: .day, in: .month, for: date)?.count ?? 31
    }
}
extension KLMDateTimePickerView: UIPickerViewDelegate {
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        guard let index = components.firstIndex(where: { $0 == .year }) else { return DefaultPickerWidth }
        let type = components[index]
        switch type {
            case .year:
                return DefaultPickerWidth + 10.0 // 当前日期前后10年
            default:
                return DefaultPickerWidth
        }
    }
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 36.0
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        var pickIndex = component
        if let index = pickers.firstIndex(of: pickerView), showUnitLabels {
            pickIndex = index
        }
        let type = components[pickIndex]
        
        switch type {
        case .year:
            dateComponents.year = currentDateComponents.year! - DefaultYearMinus + row
            updateDayComponent()
        case .month:
            dateComponents.month = row + 1
            updateDayComponent()
        case .day:
            dateComponents.day = row + 1
        case .hour:
            dateComponents.hour = row
        case .minute:
            dateComponents.minute = row
        case .second:
            dateComponents.second = row
        }
        // 强制刷新
        pickerView.reloadComponent(component)
    }
    // 更新天数时刷新Picker
    private func updateDayComponent() {
        guard let year = dateComponents.year,
              let month = dateComponents.month,
              let dayIndex = components.firstIndex(of: .day) else { return }
        
        let days = daysInMonth(year: year, month: month)
        let picker = pickers[dayIndex]
        picker.reloadComponent(0)
        
        if let currentDay = dateComponents.day, currentDay > days {
            dateComponents.day = days
            picker.selectRow(days - 1, inComponent: 0, animated: true)
        }
    }
=======
class KLMDateTimePickerView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

>>>>>>> c9ff26f7439158038ece58549346ff469099cbd4
}
